﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMS.Common
{
    public static class ModelStateExtension
    {
        /// <summary>
        /// 验证返回错误信息字典，验证通过返回null
        /// </summary>
        /// <param name="model">验证模型</param>
        /// <returns></returns>
        public static Dictionary<string, string> Validate(this object model)
        {
            Dictionary<string, string> errorMessages = null;
            ValidationContext context = new ValidationContext(model);
            List<ValidationResult> results = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(model, context, results, true);
            if (!isValid)
            {
                errorMessages = new Dictionary<string, string>();
                foreach (var item in results)
                {
                    string key = string.Join(",", item.MemberNames);
                    errorMessages.Add(key, item.ErrorMessage);
                }
            }
            return errorMessages;
        }
    }
}

